package app

import (
	"context"
	"fmt"
	"qrsj-assistant/backend/hotkey"
	"qrsj-assistant/backend/utils"

	"github.com/wailsapp/wails/v2/pkg/runtime"
)

type HotkeyApp struct {
	ctx   context.Context
	hkMap map[int64]string
}

func NewHotkeyApp() *HotkeyApp {
	return &HotkeyApp{}
}

func (a *HotkeyApp) Startup(ctx context.Context) {
	a.ctx = ctx
	a.hkMap = make(map[int64]string)
}

func (a *HotkeyApp) Shutdown(ctx context.Context) {
	a.UnregisterAllHotkeys()
}

func (a *HotkeyApp) RegisterHotkey(key string, id int64) {
	key = utils.ParseHotkey(key)
	if a.hkMap[id] != "" {
		a.UnregisterHotkey(id)
	}
	a.hkMap[id] = key
	fmt.Println("RegisterHotkey", key, id)
	hotkey.Register(key, "down", func() {
		fmt.Println("down", key, id)
		runtime.EventsEmit(a.ctx, "writeCoord", id)
	})
}

func (a *HotkeyApp) UnregisterHotkey(id int64) {
	key := a.hkMap[id]
	hotkey.Unregister(key, "down")
	delete(a.hkMap, id)
}

func (a *HotkeyApp) UnregisterAllHotkeys() {
	for _, key := range a.hkMap {
		hotkey.Unregister(key, "down")
	}
	a.hkMap = make(map[int64]string)
}
